<script lang="ts" setup>
import { RandomPointCoordinates } from '@/utils'
import { Feature, Map, Overlay } from 'ol';
import { Point } from 'ol/geom';
import { Cluster, Vector } from 'ol/source';
import { Vector as LayerVerctor } from 'ol/layer'
import { Style, Fill, Text, Icon } from 'ol/style';
import { nextTick, ref, onUnmounted } from 'vue';
import { getMap, toInitial } from '@/map';
import { Ref } from 'vue'
import markerPng from '@/assets/images/marker.png'
import starPng from '@/assets/images/star.png'
import { Select } from 'ol/interaction';
import { click } from 'ol/events/condition';
import { reactive } from 'vue';
const map = getMap()?.map as Ref<Map>
const popupContent = ref<string>("")

const pointData = reactive({
    mapx: '',
    mapy: '',

})
const create = () => {
    return RandomPointCoordinates({ size: 10000 }).map((item, index) => new Feature({
        geometry: new Point(item),
        icon: index % 2 === 0 ? starPng : markerPng,
        offsetY: index % 2 === 0 ? 2 : -5,
    }))
}
var clusterSource = new Cluster({
    distance: 40,               //聚合的距离参数，即当标注间距离小于此值时进行聚合，单位是像素
    source: new Vector({
        wrapX: false,
    })
})
var clusters = new LayerVerctor({
    source: clusterSource,
    style: function (feature) {
        const features = feature.get("features")
        let size = features.length
        const text = size > 1 ? new Text({
            text: size.toString(),
            fill: new Fill({
                color: '#fff'
            }),
            offsetY: features[0].get("offsetY"), // 将值设置为负数，将文字向上偏移
            textAlign: 'center'
        }) : undefined
        return new Style({
            image: new Icon({
                src: features[0].get("icon"),
                scale: 0.5,
            }),
            text
        });
    }
})

const select = new Select({
    layers: [clusters],
    condition: click
})


const count = ref<number>(0)

const addfeatureHandler = () => count.value = clusterSource.getSource()?.getFeatures().length as number

clusterSource.on('addfeature', addfeatureHandler)

clusterSource.on('clear', addfeatureHandler)
let overlay: Overlay | undefined = undefined



nextTick(() => {
    // Vue3响应式为Proxy对象，谨慎使用， 保险可使用获取原始对象使用
    map.value?.addLayer(clusters)
    map.value?.addInteraction(select)

    overlay = new Overlay({
        element: document.getElementById('custom_popup') as HTMLElement, // 弹窗的HTML元素，你需要事先在页面中创建并设置其样式
        positioning: 'bottom-center',
        stopEvent: false,
        id: 'custom_popup',
        className: 'cverlayClassName',
        offset: [0, -10] // 设置弹窗位置的偏移量
    });
    map.value?.addOverlay(overlay); // 将弹窗添加到地图上
    select.on("select", (event) => {
        event.preventDefault()
        const selectedFeatures = event.target.getFeatures(); // 获取选择的要素集合
        const selectedFeature = selectedFeatures.item(0); // 假设只选择了一个要素
        if (selectedFeature) {
            const geometry = selectedFeature.getGeometry(); // 获取要素的几何信息
            const coordinate = geometry.getCoordinates(); // 获取要素的坐标

            pointData.mapx = coordinate[0].toString()
            pointData.mapy = coordinate[1].toString()

            // 更新弹窗的内容和位置
            overlay?.setPosition(coordinate);

        } else {
            overlay?.setPosition(undefined);
        }
    })

    clusterSource.getSource()?.addFeatures(create())
})

onUnmounted(() => {
    const map_ = toInitial(map) as Map
    map_?.removeLayer(clusters);
    map_?.removeInteraction(select)
    map_?.removeOverlay(overlay as Overlay)
    clusterSource.un('addfeature', addfeatureHandler)
    clusterSource.un('clear', addfeatureHandler)
})

const clear = () => {
    clusterSource.getSource()?.clear()

}

const add = () => {
    clusterSource.getSource()?.addFeatures(create())
}

const reset = () => {
    clear()
    clusterSource.getSource()?.addFeatures(create())
}


</script>
<template>
    <div>
        <div id="custom_popup" class="ol-popup">
            <n-input v-model:value="pointData.mapx" disabled type="text" placeholder="基本的 Input" />
            <n-input v-model:value="pointData.mapy" disabled type="text" placeholder="基本的 Input" />
        </div>
        <div class="control-list">
            <n-space class="btn-groups" align="center" justify="center">
                <n-button type="primary" @click="clear">
                    清空
                </n-button>

                <n-button type="primary" @click="add">
                    添加10000随机点位
                </n-button>

                <n-button type="primary" @click="reset">
                    重新布点
                </n-button>
            </n-space>
        </div>
        <div class="title-c">
            <n-statistic label="点位数量" tabular-nums>
                <n-number-animation ref="numberAnimationInstRef" :from="0" :to="count" />
                <template #suffix>
                    个
                </template>
            </n-statistic>
        </div>
    </div>
</template>
<style scoped>
.control-list {
    position: absolute;
    right: 100px;
    top: 20px;
    padding: 5px;
    width: 400px;
    background-color: rgba(138, 238, 238, 0.336);
    border-radius: 5px;
    z-index: 3;
}

.title-c {
    position: absolute;
    left: 20px;
    color: #000;
    top: 20;
    width: 200px;
    padding: 5px;
    background-color: rgba(138, 238, 238, 0.9);
    border-radius: 5px;
    z-index: 2;
    text-align: center;
}

.btn-groups {
    margin-top: 5px;
}

.select-label {
    display: flex;
    justify-content: center;
}

.select-label>label {
    width: 120px;
    line-height: 34px;
}

.ol-popup {
    position: absolute;
    background-color: white;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
}

.ol-popup:after,
.ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}

.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}
</style>